package com.zyao89.view.zweb.utils;

import com.alibaba.fastjson.JSONObject;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import java.io.*;

/**
 * @author Zyao89
 * 2017/11/13.
 */

public class JsUtils {
    /**
     * 构建一个“不会重复注入”的js脚本；
     *
     * @param key key
     * @param js js
     * @return 构建的脚本
     */
    public static String buildNotRepeatInjectJS(String key, String js) {
        String obj = String.format("__injectFlag_%1$s__", key);
        final StringBuilder sb = new StringBuilder();
        sb.append("javascript:try{(function(){if(window.");
        sb.append(obj);
        sb.append("){console.log('");
        sb.append(obj);
        sb.append(" has been injected');return;}window.");
        sb.append(obj);
        sb.append("=true;");
        sb.append(js);
        sb.append("}())}catch(e){console.warn(e)}");
        return sb.toString();
    }

    /**
     * 构建一个“带try catch”的js脚本；
     *
     * @param js js
     * @return 构建的脚本
     */
    public static String buildTryCatchInjectJS(String js) {
        StringBuilder sb = new StringBuilder();
        sb.append("javascript:try{");
        sb.append(js);
        sb.append("}catch(e){console.warn(e)}");
        return sb.toString();
    }

    /**
     * 构建一个“带try catch”的js调用方法；
     *
     * @param protocolName  协议名称
     * @param functionName  方法名称
     * @param frameworkUUID UUID
     * @param oJson         json对象
     * @return 字符串
     */
    public static String buildJsFunction(String protocolName, String functionName, String frameworkUUID, String oJson) {
        StringBuilder sb = new StringBuilder();
        sb.append(";try{");
        sb.append("window.").append(protocolName).append(".").append(functionName);
        sb.append("(\"").append(frameworkUUID).append("\",");
        sb.append(oJson).append(");");
        sb.append("}catch(e){console.warn(e)};");
        return sb.toString();
    }

    public static boolean isJson(String target) {
        if (target.isEmpty()) {
            return false;
        }
        boolean tag = false;
        if (target.startsWith("[")) {
            JSONObject.parseArray(target);
        } else {
            JSONObject.parseObject(target);
        }

        tag = true;
        return tag;
    }

    public static JSONObject json2Obj(String json) {
        return JSONObject.parseObject(json);
    }

    public static String assetFile2Str(Context c, String urlStr) {
//        InputStream in = null;
//        try {
////            in = c.getAssets().open(urlStr);
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
//            String line = null;
//            StringBuilder sb = new StringBuilder();
//            do {
//                line = bufferedReader.readLine();
//                if (line != null && !line.matches("^\\s*\\/\\/.*")) {
//                    sb.append(line).append('\n');
//                }
//            } while (line != null);
//
//            bufferedReader.close();
////            in.close();
//
//            return sb.toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                }
//            }
//        }
        return null;
    }

    public static String rawFile2Str(Context c, int rawID) {
        Resource resource = null;
        BufferedReader bufferedReader = null;
        try {
            resource = c.getResourceManager().getResource(rawID);
            InputStreamReader inputStreamReader = new InputStreamReader(resource, "utf-8");

            bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;
            StringBuilder sb = new StringBuilder();
            do {
                line = bufferedReader.readLine();
                if (line != null && !line.matches("^\\s*\\/\\/.*")) {
                    sb.append(line).append('\n');
                }
            } while (line != null);

            bufferedReader.close();
            resource.close();

            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NotExistException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        finally {
            if (resource != null) {
                try {
                    resource.close();
                } catch (IOException e) {
                }
            }
            if (bufferedReader != null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * js 文件将注入为第一个script引用
     *
     * @param url 链接
     * @return string
     */
    public static String webViewLoadJs(String url) {
        String js = "var newScript = document.createElement(\"script\");";
        js += "newScript.src=\"" + url + "\";";
        js += "document.scripts[0].parentNode.insertBefore(newScript,document.scripts[0]);";
        return js;
    }

    /**
     * 不支持版本
     *
     * @return true/false
     */
    public static boolean notSupportInterface() {
        return true;
    }
}
